<?php

namespace app\common\validate;

class AddressValidate extends BaseValidate
{
    /**
     * 定义验证规则
     * 格式：'字段名'	=>	['规则1','规则2'...]
     *
     * @var array
     */	
	protected $rule = [
        'provinces'=>'require',
        'city'=>'require',
        'area'=>'require',
        'address_name'=>'require',
        'address_details'=>'require',
        'realname'=>'require',
        'mobile'=>'require|mobile',
        'email'=>'email',
        'zip_code'=>'zip',
        'is_default'=>'in:0,1',
        'id'=>'require|integer|isAddressExist|isUserToAddressExist'
    ];
    
    /**
     * 定义错误信息
     * 格式：'字段名.规则名'	=>	'错误信息'
     *
     * @var array
     */	
    protected $message = [];

    // 验证场景
    protected $scene = [
        // 创建
        'create'=>['provinces', 'city', 'area', 'address_name', 'address_details', 'realname', 'mobile','email','zip_code','is_default'],
        // 编辑
        'update'=>['provinces', 'city', 'area', 'address_name', 'address_details', 'realname', 'mobile','email','zip_code','is_default', 'id'],
        'addressDetail'=>['id']
    ];

    // 验证地址是否存在
    protected function isAddressExist($value, $rule='', $data='', $field='')
    {
        if (\app\common\model\Address::field('id')->find($value)) {
            return true;
        }
        return "该收货地址已不存在";
    }

    // 验证地址是否为当前用户
    protected function isUserToAddressExist($value, $rule='', $data='', $field='')
    {
        $address = \app\common\model\Address::field('user_id')->find($value);
        if ($address['user_id'] == request()->userId) {
            return true;
        }
        return "非法修改数据";
    }
}
